package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.Exception.CustomSetmealException;
import com.reggie.dto.SetmealDto;
import com.reggie.entity.Setmeal;
import com.reggie.entity.SetmealDish;
import com.reggie.mapper.SetmealMapper;
import com.reggie.service.SetmealDishService;
import com.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 78664
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2022-09-01 18:03:26
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {

    @Resource
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐同时添加对应的菜品关系
     *
     * @param setmealDto 套餐Dto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        // 保存套餐
        this.save(setmealDto);
        // 保存套餐菜品关系
        setmealDishService.saveBatch(
                setmealDto.getSetmealDishes()
                        .stream()
                        .peek(setmealDish -> {
                            setmealDish.setSetmealId(setmealDto.getId().toString());
                        })
                        .collect(Collectors.toList())
        );
    }

    /**
     * 删除套餐以及相对应菜品关系
     *
     * @param ids 套餐id
     */
    @Override
    @Transactional
    public void removeWithDishes(List<Long> ids) {
        // 查询是否停售
        this.listByIds(ids).forEach(setmeal -> {
            if (setmeal.getStatus() == 1) {
                throw new CustomSetmealException("起售中无法删除");
            }
        });
        // 删除套餐
        this.removeByIds(ids);
        // 删除套餐菜品关系
        LambdaQueryWrapper<SetmealDish> queryWrapper = Wrappers.lambdaQuery(SetmealDish.class);
        queryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper);
    }

    @Override
    public SetmealDto getDate(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        //在关联表中查询，setmealdish
        queryWrapper.eq(id != null, SetmealDish::getSetmealId, id);

        if (setmeal != null) {
            BeanUtils.copyProperties(setmeal, setmealDto);
            List<SetmealDish> list = setmealDishService.list(queryWrapper);
            setmealDto.setSetmealDishes(list);
            return setmealDto;
        }
        return null;
    }
}




